package com.qiaofang.applet.common.client.yxim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiaofang.applet.common.client.yxim.model.YxProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * 网易云信IM request
 * @author junze.liu
 */
@Slf4j
public class YxRequest {

    public static <T> T request(String path, Object data, Class<T> clazz, YxProperties config) {
        try {
            MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
            if (data != null) {
                BeanMap beanMap = BeanMap.create(data);
                for (Object key : beanMap.keySet()) {
                    if(beanMap.get(key) == null){
                        continue;
                    }
                    map.add(key.toString(), beanMap.get(key));
                }
            }
            JSONObject json = request(path, map, config);
            if(json == null) {
                return null;
            }
            return JSON.parseObject(json.toJSONString(), clazz);
        } catch (Exception e) {
            log.error("网易云信接口调用失败，{}", e);
        }
        return null;
    }

    public static JSONObject request(String url, MultiValueMap<String,Object> map, YxProperties config){
        try {
            log.info("yxim request map:{}", JSON.toJSONString(map));
            //随机数（最大长度128个字符）
            String nonce = RandomStringUtils.randomAlphanumeric(20);
            //当前UTC时间戳，从1970年1月1日0点0分0 秒开始到现在的秒数(String)
            String curTime = String.valueOf(System.currentTimeMillis() / 1000L);
            //SHA1(AppSecret + Nonce + CurTime)，三个参数拼接的字符串，进行SHA1哈希计算，转化成16进制字符(String，小写)
            String checkSum = YxUtil.getCheckSum(config.getAppSecret(), nonce, curTime);
            //拼接云信url
            String yxUrl = config.getAppServer() + url;

            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            requestHeaders.add("AppKey", config.getAppKey());
            requestHeaders.add("Nonce", nonce);
            requestHeaders.add("CurTime", curTime);
            requestHeaders.add("CheckSum", checkSum);
            RestTemplate restTemplate = new RestTemplate();
            log.info("yxim request requestHeaders:{}", JSON.toJSONString(requestHeaders));
            HttpEntity<MultiValueMap<String,Object>> requestEntity = new HttpEntity<>(map, requestHeaders);
            JSONObject result = restTemplate.postForEntity(yxUrl, requestEntity, JSONObject.class).getBody();
            log.info("yxim response:{}", result);
            if(!"200".equals(result.getString("code"))) {
                log.error("网易云信接口调用失败，{}", result);
                return null;
            }
            return result;
        } catch (Exception e) {
            log.error("网易云信接口调用失败，{}", e);
        }
        return null;
    }
}
